import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Layout from '@/views/layout'
import store from '@/store'
// 懒加载
const Dashboaed = () => import('@/views/dashboard')
const Article = () => import('@/views/article')

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: '/dashboard',
      children: [
        {
          path: '/dashboard',
          component: Dashboaed
        },
        { path: '/article', component: Article }
      ]
    }
  ]
})
router.beforeEach((to, from, next) => {
  // to and from are both route objects. must call `next`.
  if (to.path === '/login') {
    next()
  } else {
    const token = store.state.user.token
    if (token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
